/*
 * timer.cpp
 *
 *  Created on: 22.02.2013
 *      Author: Roma Jam
 */

#include "timer.h"
#include "Iwire.h"
#include "stm32f10x_tim.h"
#include "kl_lib.h"

//Timer_t IWireTimer;

void Timer_t::Init(){
    NVIC_InitTypeDef NVIC_InitStructure;
    /* Enable the TIM2 global Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);


    // Seek time is 1us == 1000000 Hz == 1MHz == FCLK / 8
    TIM_TimeBaseInitTypeDef TIM_TimeStructure;
    TIM_TimeStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeStructure.TIM_ClockDivision = 0;
    TIM_TimeStructure.TIM_Period = 8;
    TIM_TimeStructure.TIM_Prescaler = ((uint16_t)SystemCoreClock / 10000);
    TIM_TimeStructure.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM3, &TIM_TimeStructure);
    // Enable Timer
    TIM_Cmd(TIM3, ENABLE);
    // Clear Timer update pending bit
    TIM_ClearFlag(TIM3, TIM_FLAG_Update);
    // Interrupts config
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
}

bool Timer_t::Elapsed(uint32_t *AVar, const uint32_t ADelay_us) {
    if ((Counter - *AVar) >= ADelay_us) {
        *AVar = Counter; // Reset delay
        return true;
    }
    else return false;
}

void TIM3_IRQHandler(){
    // Clear TIM3 update interrupt
//    Uart.Printf("%u\r", IWireTimer.Counter);
    TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    IWire.IWireTimer.Counter++;

}


